package top.yokey.android.activity;

import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import top.yokey.android.R;
import top.yokey.android.base.BaseActivity;

public class WebActivity extends BaseActivity {

    private AppCompatEditText linkEditText;
    private AppCompatTextView goTextView;
    private WebView mainWebView;
    private AppCompatImageView backImageView;
    private AppCompatImageView refreshImageView;
    private AppCompatImageView forwardImageView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_web);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {

        linkEditText = findViewById(R.id.linkEditText);
        goTextView = findViewById(R.id.goTextView);
        mainWebView = findViewById(R.id.mainWebView);
        backImageView = findViewById(R.id.backImageView);
        refreshImageView = findViewById(R.id.refreshImageView);
        forwardImageView = findViewById(R.id.forwardImageView);
        mainWebView.loadUrl("https://www.baidu.com/");
        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);        //启用JavaScript支持
        webSettings.setUseWideViewPort(true);        //缩放界面
        webSettings.setLoadWithOverviewMode(true);//缩放界面
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//设置缓存方式为默认
        webSettings.setAllowFileAccess(true);//允许访问文件
        webSettings.setLoadsImagesAutomatically(true);//自动加载图片


    }

    @Override
    public void initEvent() {

        goTextView.setOnClickListener(view -> {
            String link = linkEditText.getText().toString();
            if (link.isEmpty()) return;
            if (link.contains("http://") || link.contains("https://")) {
                mainWebView.loadUrl(link);
            } else {
                mainWebView.loadUrl("https://" + link);
            }
        });

        mainWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                mainWebView.loadUrl(request.getUrl().toString());
                return true;
            }
        });

        backImageView.setOnClickListener(view->{
            mainWebView.goBack();
        });

        refreshImageView.setOnClickListener(view->{
            mainWebView.reload();
        });

        forwardImageView.setOnClickListener(view->{
            mainWebView.goForward();
        });

    }

}
